package com.haitonghop.main;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.widget.Toast;

import com.haitonghop.controls.OnSaveComic;
import com.haitonghop.controls.onUserCreateTopic;
import com.haitonghop.data.HaiBLMetalData;
import com.haitonghop.modules.haivl.HaiVLActivity;
import com.haitonghop.utils.Logger;
import com.haitonghop.utils.sqllite.datasource.ComicsCachedDataSource;
import com.haitonghop.utils.sqllite.datasource.TopicHaiBLDataSource;
import com.haitonghop.utils.sqllite.datasource.TopicHaiBlData;

public class ComicBussiness {

	private ComicsCachedDataSource comicsCachedDataSource = null;
	private TopicHaiBLDataSource topicHaiBLDataSource = null;
	private ArrayList<TopicHaiBlData> currentTopicListDB = null;
	private TopicHaiBlData currentTopicListUsage = null;

	private static ComicBussiness comicBussiness = null;

	private boolean isGotTopicListFormDB = false;

	private ComicBussiness(Context context) {
		comicsCachedDataSource = new ComicsCachedDataSource(context);
		topicHaiBLDataSource = new TopicHaiBLDataSource(context);
	}

	public static ComicBussiness getInstance(Context context) {
		if (comicBussiness == null && context != null) {
			comicBussiness = new ComicBussiness(context);
		}
		return comicBussiness;
	}

	public void setDefaultComicTopic(TopicHaiBlData topicListUsage) {
		currentTopicListUsage = topicListUsage;
	}

	public TopicHaiBlData getDefaultComicTopic() {
		return currentTopicListUsage;
	}

	public ArrayList<TopicHaiBlData> getComicTopicList() {
		if (currentTopicListDB == null || (currentTopicListDB != null && currentTopicListDB.isEmpty() && !isGotTopicListFormDB)) {
			isGotTopicListFormDB = true;
			currentTopicListDB = topicHaiBLDataSource.getAllTopic();
		}
		return currentTopicListDB;
	}
	
	public boolean isDefaultTopicHasExists(int id) {
		getComicTopicList();
		if (currentTopicListDB == null || (currentTopicListDB != null && currentTopicListDB.isEmpty()))
			return false;
		else {
			for (int i = 0, n = currentTopicListDB.size(); i < n; i++) {
				TopicHaiBlData tmp = currentTopicListDB.get(i);
				if (tmp.getId() == id) {
					return true;
				}
			}
			return false;
		}
	}
	
	private HaiBLMetalData cursorToHaiBLMetalData(Cursor cursor) {
		HaiBLMetalData object = new HaiBLMetalData();
		object.setTitleDescription(cursor.getString(1));	
		object.setImageUrl(cursor.getString(2));
		return object;
	}	
	
	public ArrayList<HaiBLMetalData> getComicFromDataBase(int mainIdTopic){
		ArrayList<HaiBLMetalData> datas = null;
		if(mainIdTopic != -1){			
			Cursor cursor = comicsCachedDataSource.getComicDataSQL(mainIdTopic);
			if(cursor != null){
				ArrayList<HaiBLMetalData> arrayList = new ArrayList<HaiBLMetalData>();
				for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
					arrayList.add(cursorToHaiBLMetalData(cursor));
				}
						
				datas = new ArrayList<HaiBLMetalData>(arrayList.size());
				for(int i = arrayList.size() -1 ; i >= 0 ; i--){
					datas.add(arrayList.get(i));
				}
			}
		}
		return datas;
	}
	
	public boolean isDeletedComicAsync(){
		return isDeletedComic;
	}

	public boolean isDeletedComic = false;

	public void deletedComicAsync(final ArrayList<HaiBLMetalData> datas) {
		if (!isDeletedComic) {
			isDeletedComic = true;
			new Thread(new Runnable() {

				public void run() {
					Logger.logMe("<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
					if (datas != null && comicsCachedDataSource != null) {
						for (int i = 0; i < datas.size(); i++) {
							Logger.logMe("<<<<<<<<<<<<<<<<<<<<<<<<<<<< "+i);
							comicsCachedDataSource.deletedComic(datas.get(i));
						}
					}
					isDeletedComic = false;
				}
			});
		}		
	}

	public boolean deletedComic(final ArrayList<HaiBLMetalData> datas) {
		if (datas != null && comicsCachedDataSource != null) {
			for (int i = 0; i < datas.size(); i++) {
				comicsCachedDataSource.deletedComic(datas.get(i));
			}
		}
		return false;
	}

	public boolean deletedComic(final Context context, final HaiBLMetalData data) {
		if (context != null && data != null) {
			if (comicsCachedDataSource != null) {
				return comicsCachedDataSource.deletedComic(data);
			}
		}
		return false;
	}

	public boolean changeTopicName(final Context context, final TopicHaiBlData topicHaiBlData, final String newName) {
		if (context != null && topicHaiBlData != null && topicHaiBlData.getId() != -1) {			
			if(currentTopicListUsage != null && currentTopicListUsage.getId() == topicHaiBlData.getId()){
				Logger.logMe("currentTopicListUsage.getId() "+currentTopicListUsage.getId());
				Logger.logMe("topicHaiBlData.getId() "+topicHaiBlData.getId());
				
				Logger.logMe("currentTopicListUsage.getName() "+currentTopicListUsage.getName());
				Logger.logMe("newName "+newName);
				
				currentTopicListUsage.setName(newName);
			}
			ComicSessionStore.saveDefaultTopic(currentTopicListUsage, context);
			
			if (currentTopicListDB != null) {
				final int size = currentTopicListDB.size();
				for (int i = 0; i < size; i++) {
					TopicHaiBlData item = currentTopicListDB.get(i);
					if (item.getId() == topicHaiBlData.getId()) {
						item.setName(newName);
						break;
					}
				}
			}

			return topicHaiBLDataSource.changeTopicName(topicHaiBlData.getId(), newName);
		}
		return false;
	}

	public boolean doDeletedTopic(final Context context, final TopicHaiBlData topicHaiBlData) {
		if (context != null && topicHaiBlData != null && topicHaiBlData.getId() != -1) {
			ComicSessionStore.clearDefaultTopic(context);

			if (currentTopicListUsage != null && currentTopicListUsage.getId() == topicHaiBlData.getId()) {
				currentTopicListUsage = null;
			}

			if (currentTopicListDB != null) {
				final int size = currentTopicListDB.size();
				for (int i = 0; i < size; i++) {
					TopicHaiBlData item = currentTopicListDB.get(i);
					if (item.getId() == topicHaiBlData.getId()) {
						currentTopicListDB.remove(i);
						break;
					}
				}
			}

			boolean isDoneDeletedTopic = topicHaiBLDataSource.deletedTopicWithId(topicHaiBlData.getId());
			if(isDoneDeletedTopic){
				return comicsCachedDataSource.deletedComic(topicHaiBlData.getId());
			}
			return isDoneDeletedTopic;
		}
		return false;
	}

	public void doSaveCommicToDefault(final Context context, final HaiBLMetalData blMetalData, final OnSaveComic listener) {
		if (blMetalData != null) {
			if (currentTopicListUsage != null && currentTopicListUsage.getId() != -1) {
				// Save to topic default
				insertComicToDataBase(context, blMetalData, currentTopicListUsage, listener);
			} else {
				if (listener != null) {
					listener.onError(OnSaveComic.DEFAULT_TOPIC_NOTFOUND);
				}
			}
		} else {
			if (listener != null) {
				listener.onError(OnSaveComic.IMAGE_NOT_FOUND);
			}
		}
	}

	public void doSaveCommic(final Context context, final HaiBLMetalData blMetalData, final OnSaveComic listener) {
		if (blMetalData != null) {
			if (currentTopicListDB == null) {
				getComicTopicList();
			}

			if (currentTopicListDB == null || (currentTopicListDB != null && currentTopicListDB.isEmpty())) {
				// user need create a topic
				createNewTopic(context, blMetalData, listener);
			} else {
				showTopicListsDialogChoice(context, blMetalData, listener);
			}
		} else {
			if (listener != null) {
				listener.onError(OnSaveComic.IMAGE_NOT_FOUND);
			}
		}
	}

	void createNewTopic(final Context context, final HaiBLMetalData blMetalData, final OnSaveComic listener) {
		DisplayUtils.openDialogEnterNameTopic(context, new onUserCreateTopic() {

			public void onCreate(String name) {
				if (name != null && !"".equals(name) && blMetalData != null) {
					TopicHaiBlData haiBlData = new TopicHaiBlData(name);

					int topicIdCreated = (int) topicHaiBLDataSource.insertTopic(haiBlData);
					if (topicIdCreated != -1) {

						Logger.logMe("Create topic done with id = " + topicIdCreated);
						haiBlData.setId(topicIdCreated);

						// insert to mem
						if (currentTopicListDB == null)
							currentTopicListDB = new ArrayList<TopicHaiBlData>();
						currentTopicListDB.add(haiBlData);

						insertComicToDataBase(context, blMetalData, haiBlData, listener);
					} else {
						if (listener != null)
							listener.onError(OnSaveComic.CREATE_TOPIC_ERROR);
					}
				} else {
					if (listener != null) {
						if (blMetalData == null) {
							listener.onError(OnSaveComic.IMAGE_NOT_FOUND);
						} else {
							listener.onError(OnSaveComic.TOPIC_NAME_INVAILD);
						}
					}
				}
			}

			public void onCancel() {

			}
		});
	}

	AlertDialog topicListDialogChoicer = null;

	void showTopicListsDialogChoice(final Context context, final HaiBLMetalData blMetalData, final OnSaveComic listener) {
		if (currentTopicListDB != null && !currentTopicListDB.isEmpty()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle("Danh sách chủ đ�?");

			final String[] choiceList = new String[currentTopicListDB.size()];
			final int size = currentTopicListDB.size();
			for (int index = 0; index < size; index++) {
				choiceList[index] = currentTopicListDB.get(index).getName();
			}
			int selected = -1;
			builder.setSingleChoiceItems(choiceList, selected, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					final TopicHaiBlData haiBlData = currentTopicListDB.get(which);
					topicListDialogChoicer.dismiss();
					insertComicToDataBase(context, blMetalData, haiBlData, listener);
				}
			});

			builder.setNegativeButton("�?óng", null);
			builder.setNeutralButton("Tạo mới", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					createNewTopic(context, blMetalData, listener);
				}
			});
			topicListDialogChoicer = builder.create();
			topicListDialogChoicer.show();
		} else {
			if (listener != null) {
				listener.onError(OnSaveComic.DB_NOT_FOUND);
			}
		}
	}

	void insertComicToDataBase(final Context context, final HaiBLMetalData blMetalData, final TopicHaiBlData haiBlData, final OnSaveComic listener) {
		if (blMetalData != null && haiBlData != null) {
			boolean isDone = comicsCachedDataSource.insertComicCached(blMetalData, haiBlData);
			if (isDone) {
				Toast.makeText(context, "�?ã thêm truyện vào chủ đ�? \"" + haiBlData.getName() + "\"", 1000).show();

				if (currentTopicListUsage == null) {
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle("Chủ đ�? mặc định");
					builder.setMessage("Bạn có muốn sử dụng " + haiBlData.getName() + " làm chủ đ�? mặc định để lưu truyện?");
					builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							if (listener != null) {
								listener.onDone(blMetalData, haiBlData);
							}
						}

					});
					builder.setPositiveButton("Có", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							currentTopicListUsage = new TopicHaiBlData(haiBlData.getId(), haiBlData.getName());
							ComicSessionStore.saveDefaultTopic(currentTopicListUsage, context);

							if (listener != null) {
								listener.onDoneWithNewTopic(blMetalData, currentTopicListUsage);
							}
						}
					});
					topicListDialogChoicer = builder.create();
					topicListDialogChoicer.show();
				} else {
					if (listener != null) {
						listener.onDone(blMetalData, haiBlData);
					}
				}
			} else {
				if (listener != null) {
					listener.onError(OnSaveComic.INSERT_COMIC_ERROR);
				}
				Toast.makeText(context, "Lỗi, không thể thêm truyện vào chủ đ�? \"" + haiBlData.getName() + "\"!", 1000).show();
			}
		} else {
			if (listener != null) {
				if (blMetalData == null) {
					listener.onError(OnSaveComic.IMAGE_NOT_FOUND);
				} else if (haiBlData == null) {
					listener.onError(OnSaveComic.TOPIC_NOTFOUND);
				} else {
					listener.onError(OnSaveComic.INSERT_COMIC_ERROR);
				}
			}
			Toast.makeText(context, "Lỗi, không thể thêm truyện vào máy!", 1000).show();
		}
	}

}
